package top.infopub.mgr.fia.web;


import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.fia.domain.ProBudgetDomain;
import top.infopub.mgr.fia.service.ProBudgetService;
import top.infopub.mgr.fia.vo.ProBudgetVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.service.DiscloseProService;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.fia.ProBudget;
import top.infopub.model.fia.ProBudgetDetail;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.DisclosePro;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * 项目指标预算管理
 * @author wangw
 * @version 2020年1月15日
 * @see ProBudgetController
 * @since
 */
@Controller
@RequestMapping("/proBudget")
public class ProBudgetController extends GenericFlowController {

    @Autowired
    private ProBudgetService proBudgetService;

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private DiscloseProService discloseProService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    /**
     * 项目指标预算列表
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        String bindOrgId = (String)SessionUserUtils.getSessionAttribute("bindOrgId");
        request.setAttribute("bindOrgId", bindOrgId);
        String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        List<OrgInfo> orgInfos = new ArrayList<OrgInfo>();
        if (StringUtils.isEmpty(visibleOrgIds)) {
            OrgInfo orgInfo = new OrgInfo();
            orgInfo.setState(1);
            orgInfos = orgInfoService.selectByEntityWhere(orgInfo);
        }
        else {
            orgInfos = orgInfoService.selectByVisibleIds(visibleOrgIds);
        }
        request.setAttribute("orgInfos", orgInfos);
        return "fia/lay-proBudget-list";
    }

    /**
     * 项目指标预算列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<ProBudgetDomain> queryDataByCondition(ProBudgetVo proBudgetVo, ParamPage paramPage) {
        Page<ProBudgetDomain> page = new Page<ProBudgetDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (proBudgetVo.getEndDate() != null) {
            proBudgetVo.setEndDate(DateUtils.addDays(proBudgetVo.getEndDate(), 1));
        }
        page = proBudgetService.selectPageByDomainWhere(page, proBudgetVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 项目指标预算-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        //查询可项目指标预算的项目指标预算记录
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        List<OrgInfo> orgInfos = new ArrayList<OrgInfo>();
        if (StringUtils.isEmpty(visibleOrgIds)) {
            OrgInfo orgInfo = new OrgInfo();
            orgInfo.setState(1);
            orgInfos = orgInfoService.selectByEntityWhere(orgInfo);
        }
        else {
            orgInfos = orgInfoService.selectByVisibleIds(visibleOrgIds);
        }
        request.setAttribute("orgInfos", orgInfos);
        //所有已交底的项目
        List<DisclosePro> disclosePros = discloseProService.selectAllDisclosePro();
        request.setAttribute("disclosePros", disclosePros);
        return "fia/lay-proBudget-add";
    }

    /**
     * 根据id查询项目指标预算详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 项目指标预算Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        ProBudgetVo proBudget = proBudgetService.selectById(id);
        map.put("proBudget", proBudget);
        return new ModelAndView("fia/lay-proBudget-detail", map);
    }

    /**
     * 新增项目指标预算
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(HttpServletRequest request, ProBudgetVo proBudget) {

        if (StringUtils.isBlank(proBudget.getId())) {
            int count = proBudgetService.count(proBudget.getBelongsYear(),proBudget.getProCode());
            //判断是否存在同一公司名称、同一预算年度已有生效中单据
            if (count > 0) {
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("已有同一公司同一预算年度单据，不可重复提交");
            }
        }

        String[] months = request.getParameterValues("months");//子项月份
        String[] caeFees = request.getParameterValues("caeFee");//子项-建安产值
        String[] finFees = request.getParameterValues("finFee");//子项-融资额
        String[] investFees = request.getParameterValues("investFee");//子项-投资额
        String[] manageProfits = request.getParameterValues("manageProfit");//子项-管理净利润
        String[] cashIns = request.getParameterValues("cashIn");//子项-投资性现金流入
        String[] cashOuts = request.getParameterValues("cashOut");//子项-投资性现金流出

        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();

        /**
         * 项目指标预算主表处理
         */
        String id = IdFactory.getUUIDUpper();
        proBudget.setId(id);
        proBudget.setHrStaffApplyId(vo.getHrStaffId());
        proBudget.setAddBy(vo.getId());
        proBudget.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String codes = codeGeneratorConfigService.generatorCode("fia_pro_budget_codes");
        proBudget.setCodes(codes);
        // 处理processId
        //proBudget.setProcessId(IdFactory.getUUIDUpper());
        proBudget.setProcessStatus("9");//生效中
        proBudget.setUptBy(vo.getId());
        proBudget.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //子项处理
        List<ProBudgetDetail> proBudgetDetails = new ArrayList<ProBudgetDetail>();
        for (int i = 0; i < months.length; i++ ) {
            String orderId = months[i];
            ProBudgetDetail proBudgetDetail = new ProBudgetDetail();
            String subId = IdFactory.getUUIDUpper();//自动生成主键
            proBudgetDetail.setId(subId);
            proBudgetDetail.setProBudgetId(id);
            proBudgetDetail.setMonths(Integer.parseInt(orderId));
            proBudgetDetail.setCaeFee(new BigDecimal(caeFees[i]));
            proBudgetDetail.setFinFee(new BigDecimal(finFees[i]));
            proBudgetDetail.setInvestFee(new BigDecimal(investFees[i]));
            proBudgetDetail.setManageProfit(new BigDecimal(manageProfits[i]));
            proBudgetDetail.setCashIn(new BigDecimal(cashIns[i]));
            proBudgetDetail.setCashOut(new BigDecimal(cashOuts[i]));
            proBudgetDetail.setAddBy(vo.getId());
            proBudgetDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            proBudgetDetails.add(proBudgetDetail);
        }

        proBudgetService.addProBudget(proBudget, proBudgetDetails);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD,
            "项目指标预算 -新增项目指标预算：项目名称=" + proBudget.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 修改项目指标预算状态
     * @param 
     * @return 
     * @see
     */
    @RequestMapping("/updateStatus")
    public @ResponseBody RspVo<String> updateStatus(String id) {
        ProBudget budget = proBudgetService.selectByPrimaryKey(id);
        String oldStatus = budget.getProcessStatus();
        String newStatus = "9";
        if ("9".equals(oldStatus)) {
            newStatus = "10";
        }
        else {
            newStatus = "9";
        }
        budget.setProcessStatus(newStatus);
        budget.setUptTime(new Date());
        budget.setUptBy(SessionUserUtils.getSessionUserId());
        proBudgetService.updateBySelective(budget);
        // 操作日志
        LogUtil.bizLog(
            LogUtil.LogModelType.OTHER,
            LogUtil.AcctionType.UPDATE,
            "修改状态  项目指标预算表单据ID:" + budget.getCodes(),"");
        return RspVo.getSuccessResponse();
    }

    /**
     * 编辑项目指标预算表
     * @param payBillVo
     * @return 
     * @throws NoSuchMethodException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     * @see
     */
    @RequestMapping("/update")
    public @ResponseBody RspVo<ProBudgetVo> update(ProBudgetVo proBudgetVo) {
        proBudgetService.udpProBudget(proBudgetVo);
        LogUtil.bizLog(LogModelType.OTHER, AcctionType.UPDATE, "修改项目指标预算表 - 项目指标预算表Id:"
                                                               + proBudgetVo.getId(), null);
        return RspVo.getSuccessResponse(proBudgetVo);
    }

}
